package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ClientTest {
    private Socket socket;
    public ClientTest(){
        try {
            System.out.println("正在连接服务端...");
            socket=new Socket("localhost",8088);
            System.out.println("成功连接服务端");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            OutputStream out = socket.getOutputStream();
            //out.write(1);
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);

            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);

            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入要发送的内容,输入exit退出！");
            while (true) {
                String msg = scanner.nextLine();
                if("exit".equalsIgnoreCase(msg)){break;}
                pw.println(msg);
                System.out.println("发送成功");

                msg=br.readLine();//读取服务端发送来的消息
                System.out.println("接收到服务端消息："+msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        Client1 client=new Client1();
        client.start();
    }
}
